package com.biodiv.community.filter;

import cn.hutool.core.lang.UUID;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import static com.biodiv.community.constant.CommonConstant.TRACE_ID;

/**
 * @author tianquan
 */
@Slf4j
@Component
public class TraceIdRelayFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 1.生成 traceId
        String traceId = UUID.randomUUID().toString(true);
        // 2.保存到日志变量池
        MDC.put(TRACE_ID, traceId);
        // 3.traceId向下传递
        exchange = exchange.mutate().request(request -> {
                    request.header(TRACE_ID, traceId);
                }
        ).build();

        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE;
    }
}
